package com.xinling.modules.chat.service.impl;

import com.xinling.modules.chat.model.dto.ArkRequest;
import com.xinling.modules.chat.model.dto.ArkResponse;
import com.xinling.modules.chat.model.dto.ChatMessage;
import com.xinling.modules.chat.model.entity.ChatSession;
import com.xinling.modules.chat.service.ChatService;
import com.xinling.modules.chat.service.ChatHistoryService;
import com.xinling.modules.user.mapper.UserMapper;
import com.xinling.modules.user.model.entity.User;
import com.xinling.security.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
public class ChatServiceImpl implements ChatService {
    private static final Logger logger = LoggerFactory.getLogger(ChatServiceImpl.class);

    @Value("${ark.api.key}")
    private String arkApiKey;

    @Value("${ark.api.url}")
    private String arkApiUrl;

    private final RestTemplate restTemplate;
    private final ChatHistoryService chatHistoryService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    public ChatServiceImpl(RestTemplate restTemplate, ChatHistoryService chatHistoryService) {
        this.restTemplate = restTemplate;
        this.chatHistoryService = chatHistoryService;
    }

    @Async
    public List<String> generateSuggestedQuestions(String aiResponse) {
        logger.info("开始生成推荐问题，基于AI回答: {}", aiResponse);
        try {
            // 创建专门的prompt来生成推荐问题
            String prompt = "基于以下AI回答内容，生成5个用户可能想继续追问的相关问题，每个问题用|||分隔：\n\n" + aiResponse;
            
            // 创建Ark API请求
            ArkRequest arkRequest = new ArkRequest();
            arkRequest.setModel("deepseek-v3-250324");
            
            List<ArkRequest.Message> messages = new ArrayList<>();
            ArkRequest.Message systemMessage = new ArkRequest.Message();
            systemMessage.setRole("system");
            systemMessage.setContent("你是一个问题推荐助手，请分析AI回答并生成相关的后续问题。");
            messages.add(systemMessage);
            
            ArkRequest.Message userMessage = new ArkRequest.Message();
            userMessage.setRole("user");
            userMessage.setContent(prompt);
            messages.add(userMessage);
            
            arkRequest.setMessages(messages);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + arkApiKey);

            // 发送请求到Ark API
            ArkResponse response = restTemplate.postForObject(
                arkApiUrl + "chat/completions",
                new HttpEntity<>(arkRequest, headers),
                ArkResponse.class
            );

            if (response != null && !response.getChoices().isEmpty()) {
                String suggestionsResponse = response.getChoices().get(0).getMessage().getContent();
                // 分割回答得到问题列表
                return Arrays.asList(suggestionsResponse.split("\\|\\|\\|"));
            }
        } catch (Exception e) {
            logger.error("生成推荐问题时发生错误: {}", e.getMessage(), e);
        }
        return new ArrayList<>();
    }

    @Override
    public ChatMessage handleMessage(ChatMessage message) {
        logger.info("收到前端消息: {}", message);
        message.setTimestamp(System.currentTimeMillis());

        if (message.getSessionId() == null) {
            ChatSession session = chatHistoryService.createSession(getCurrentUserId(), "新对话");
            message.setSessionId(session.getId());
        }

        chatHistoryService.saveMessage(message.getSessionId(), "user", message.getContent(), message.getModel());
        
        // 发送到Ark API并获取响应（包含推荐问题）
        ChatMessage response = sendToArk(message);
        
        // 保存AI响应
        chatHistoryService.saveMessage(message.getSessionId(), "assistant", response.getContent(), response.getModel());

        // 更新会话标题（如果需要）
        if (message.getSessionId() != null) {
            ChatSession session = chatHistoryService.getSession(message.getSessionId());
            if (session != null && "新对话".equals(session.getTitle())) {
                String title = message.getContent().length() > 20 
                    ? message.getContent().substring(0, 20) + "..."
                    : message.getContent();
                chatHistoryService.updateSessionTitle(message.getSessionId(), title);
            }
        }
        
        return response;
    }

    @Override
    public ChatMessage sendToArk(ChatMessage message) {
        logger.info("开始调用Ark API，用户消息内容: {}", message.getContent());
        try {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + arkApiKey);
            logger.debug("Ark API请求头: {}", headers);

            // 创建Ark API请求
            ArkRequest arkRequest = new ArkRequest();
            arkRequest.setModel("deepseek-v3-250324");
            
            List<ArkRequest.Message> messages = new ArrayList<>();
            // 添加系统消息
            ArkRequest.Message systemMessage = new ArkRequest.Message();
            systemMessage.setRole("system");
            systemMessage.setContent("You are a helpful assistant.");
            messages.add(systemMessage);
            
            // 添加用户消息
            ArkRequest.Message userMessage = new ArkRequest.Message();
            userMessage.setRole("user");
            userMessage.setContent(message.getContent());
            messages.add(userMessage);
            
            arkRequest.setMessages(messages);
            
            logger.info("准备发送到Ark API的请求体: {}", arkRequest);

            // 发送请求到Ark API
            logger.info("正在发送请求到Ark API: {}", arkApiUrl + "chat/completions");
            ArkResponse response = restTemplate.postForObject(
                arkApiUrl + "chat/completions",
                new HttpEntity<>(arkRequest, headers),
                ArkResponse.class
            );
            logger.info("收到Ark API响应: {}", response);

            // 创建聊天消息响应
            ChatMessage chatResponse = new ChatMessage();
            chatResponse.setType("ark_response");
            if (response != null && !response.getChoices().isEmpty()) {
                String aiResponse = response.getChoices().get(0).getMessage().getContent();
                logger.info("AI助手回复内容: {}", aiResponse);
                chatResponse.setContent(aiResponse);
                
                // 生成推荐问题
                List<String> suggestedQuestions = generateSuggestedQuestions(aiResponse);
                
                // 如果没有生成推荐问题，则基于最近的对话重新生成
                if (suggestedQuestions == null || suggestedQuestions.isEmpty()) {
                    logger.info("未生成推荐问题，基于最近对话重新生成");
                    String contextPrompt = "基于以下对话上下文，生成5个用户可能感兴趣的相关问题：\n\n" +
                                        "用户：" + message.getContent() + "\n\n" +
                                        "AI：" + aiResponse;
                    suggestedQuestions = generateSuggestedQuestionsWithContext(contextPrompt);
                }
                
                logger.info("推荐问题列表: {}", suggestedQuestions);
                chatResponse.setSuggestedQuestions(suggestedQuestions);
            } else {
                logger.warn("Ark API返回空响应或无选择");
                chatResponse.setContent("未收到Ark API的有效响应");
            }
            chatResponse.setTimestamp(System.currentTimeMillis());

            return chatResponse;
        } catch (Exception e) {
            logger.error("调用Ark API时发生错误: {}", e.getMessage(), e);
            // 创建错误响应
            ChatMessage errorResponse = new ChatMessage();
            errorResponse.setType("error");
            errorResponse.setContent("调用Ark API失败: " + e.getMessage());
            errorResponse.setTimestamp(System.currentTimeMillis());
            return errorResponse;
        }
    }

    @Async
    public List<String> generateSuggestedQuestionsWithContext(String contextPrompt) {
        try {
            // 创建Ark API请求
            ArkRequest arkRequest = new ArkRequest();
            arkRequest.setModel("deepseek-v3-250324");
            
            List<ArkRequest.Message> messages = new ArrayList<>();
            ArkRequest.Message systemMessage = new ArkRequest.Message();
            systemMessage.setRole("system");
            systemMessage.setContent("你是一个问题推荐助手。请根据对话上下文，生成5个用户可能感兴趣的相关问题。" +
                                  "这些问题应该：\n" +
                                  "1. 与对话主题相关\n" +
                                  "2. 能够深入探讨或扩展当前话题\n" +
                                  "3. 简洁明了，每个问题不超过30个字\n" +
                                  "4. 使用|||分隔每个问题");
            messages.add(systemMessage);
            
            ArkRequest.Message userMessage = new ArkRequest.Message();
            userMessage.setRole("user");
            userMessage.setContent(contextPrompt);
            messages.add(userMessage);
            
            arkRequest.setMessages(messages);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + arkApiKey);

            // 发送请求到Ark API
            ArkResponse response = restTemplate.postForObject(
                arkApiUrl + "chat/completions",
                new HttpEntity<>(arkRequest, headers),
                ArkResponse.class
            );

            if (response != null && !response.getChoices().isEmpty()) {
                String suggestionsResponse = response.getChoices().get(0).getMessage().getContent();
                return Arrays.asList(suggestionsResponse.split("\\|\\|\\|"));
            }
        } catch (Exception e) {
            logger.error("生成上下文推荐问题时发生错误: {}", e.getMessage(), e);
        }
        return new ArrayList<>();
    }

    private Long getCurrentUserId() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attrs == null) return null;
        HttpServletRequest request = attrs.getRequest();
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) return null;
        String username = jwtTokenUtil.getUsernameFromToken(token.replace("Bearer ", ""));
        if (username == null) return null;
        User user = userMapper.findByUsername(username);
        if (user == null) return null;
        return user.getId();
    }

} 